<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="name">
              <el-input placeholder="请输入分类名称" v-model="searchForm.name" clearable>
                <template slot="prepend" v-if="searchForm.level === 0">一级分类</template>
                <template slot="prepend" v-else-if="searchForm.level === 1">二级分类</template>
                <template slot="prepend" v-else>三级分类</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search(true)">搜索</el-button>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <span>
          <el-tag style="margin-bottom:20px;margin-right:5px;cursor:pointer;" @click="goto(0,0)">顶级 /</el-tag>
          <el-tag v-if="searchForm.level == 1 || searchForm.level == 2" style="margin-bottom:20px;margin-right:5px;cursor:pointer;"
            @click="goto(level0id,1)">{{level0name}} /</el-tag>
          <el-tag v-if="searchForm.level == 2" style="margin-bottom:20px;margin-right:5px;cursor:pointer;" @click="goto(level1id,2)">
            {{level1name}} /</el-tag>
        </span>
        <el-table :data="table" border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="分类名称"></el-table-column>
          <el-table-column v-if="searchForm.level === 0 || searchForm.level === 2" label="图片" width="70">
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.pic" :fit="fit" :preview-src-list="[scope.row.pic]"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="70">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.status == 1 ?'正常': '禁用'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row,-1,-1)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button v-if="searchForm.level ==0 ||searchForm.level ==1" type="text" @click="next(scope.row)">查看下级</el-button>
              <el-button type="text" @click="edit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑分类" :visible.sync="editVisible" :before-close="handleClose('editForm')" width="500px">
        <el-form ref="editForm" :model="editForm" label-width="180px" :rules="rules">
          <el-form-item label="名称" prop="name">
            <el-input v-model="editForm.name" clearable placeholder="请输入名称"></el-input>
          </el-form-item>
          <el-form-item label="图片" v-if="editForm.level == 0 || editForm.level == 2" prop="pic">
            <el-upload ref="editImage" name="image" action="#" :on-change="handleImgChange" :on-remove="handleImgRemove" list-type="picture"
              :limit="1" :on-exceed="handleImgExceed" :auto-upload="false" :file-list="editPic">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加分类" :visible.sync="addVisible" :before-close="handleClose('addForm')" width="500px">
        <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rules">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader clearable ref="addCascader" placeholder="默认为一级分类" v-model="addForm.pid"
              :props="{ value: 'id',label:'name',children:'children',checkStrictly: true  }" :options="cateInfo" @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="图片" v-if="addForm.pid.length == 0 | addForm.pid.length == 2" prop="pic">
            <el-upload ref="addImage" name="image" action="#" :on-change="handleImgChange" :on-remove="handleImgRemove" list-type="picture" :limit="1"
              :on-exceed="handleImgExceed" :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close()" size="small">取 消</el-button>
          <el-button type="primary" @click="send()" size="small">添 加</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { lstFirAndSec, changeCateStatus, getCateList, getCateOnly, addCate, editCate, delCate } from '@/network/api.js'

export default {
  name: 'category',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: '',
        level: 0,
        pid: 0
      },
      level0name: '',
      level1name: '',
      level0id: 0,
      level1id: 0,
      table: [],
      count: 0,
      editForm: {
        id: 0,
        name: '', // 名称
        pic: '', // 图片
        level: -1 // 父级id
      },
      editPic: [], // 编辑原始pic
      // 添加表单
      addForm: {
        name: '', // 名称
        pic: '', // 图片
        pid: [] // 父级id
      },
      actFormName: '',
      actUploadName: '',
      actvisibleName: '',
      cateInfo: [], // 一二级联级数据
      fileList: [],
      editVisible: false, // 编辑
      addVisible: false, // 添加
      rules: {
        name: [{ required: true, message: '名称必须', trigger: 'blur' }],
        pic: [{ required: true, message: '分类图片必须', trigger: 'change' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    goto(pid, level) {
      this.searchForm.name = ''
      this.searchForm.status = ''
      this.searchForm.pid = pid
      this.searchForm.level = level
      this.search()
    },
    next(row) {
      if (row.level === 0) {
        this.level0name = row.name
        this.level0id = row.id
      } else if (row.level === 1) {
        this.level1name = row.name
        this.level1id = row.id
      }
      this.searchForm.pid = row.id
      this.searchForm.level = row.level + 1
      this.searchForm.name = ''
      this.searchForm.status = ''
      this.search()
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    // 添加文件
    handleImgChange(file, fileList) {
      if (file && file.status === 'ready') {
        // 判断文件类型
        const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
        if (imageType.indexOf(file.raw.type) === -1) {
          this.$message.error('请上传png|jpg|jpeg图片')
          return this.$refs[this.actUploadName].clearFiles()
        }
        if (file.size > 1024 * 400) {
          this.$message.error('请上传小于500kb图片')
          return this.$refs[this.actUploadName].clearFiles()
        }
        this[this.actFormName].pic = file.raw
        this.$refs[this.actFormName].clearValidate('pic')
      }
    },
    handleImgRemove(file, fileList) {
      // console.log(file)
      // if (file && file.status === 'ready') {
      // 移除方法
      this[this.actFormName].pic = ''
      // console.log(this[this.actFormName])
      this.$refs[this.actFormName].validateField('pic')
      // }
    },
    // 超出上传个数
    handleImgExceed(files, fileList) {
      this.$message.error('已有pic图片请先删除')
    },
    // 联动删除
    handleChange(data) {
      this.$refs[this.actFormName].clearValidate()
    },
    async search(pageInit = false) {
      try {
        if (pageInit === true) {
          this.searchForm.page = 1
        }
        const rtn = await getCateList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    async add() {
      try {
        const rtn = await lstFirAndSec({})
        this.addVisible = true
        this.$nextTick(() => {
          this.cateInfo = rtn.cateInfo
          this.tempInfo = rtn.tempInfo
          this.actFormName = 'addForm'
          this.actvisibleName = 'addVisible'
          this.actUploadName = 'addImage'
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 修改状态
    changeStatus(ev) {
      let msg = ''
      let oldStatus = ''
      switch (ev.status) {
        case 1:
          msg = '您确定要启用该分类吗?'
          oldStatus = 2
          break
        case 2:
          msg = '此操作将禁用该分类以及旗下分类, 是否确定?'
          oldStatus = 1
          break
        default:
          return this.$message.error('不可用的操作')
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // closeOnClickModal: false
      })
        .then(async () => {
          try {
            await changeCateStatus({ id: ev.id, status: ev.status })
          } catch (e) {
            ev.status = oldStatus
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          ev.status = oldStatus
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('此操作将删除该分类以及旗下分类, 是否确定?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        // closeOnClickModal: false
      })
        .then(async () => {
          try {
            await delCate({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getCateOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.info
          this.editPic = [{ url: [rtn.info.pic] }]
          this.cateInfo = rtn.other.cateInfo
          this.tempInfo = rtn.other.tempInfo
          this.actFormName = 'editForm'
          this.actvisibleName = 'editVisible'
          this.actUploadName = 'editImage'
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    myClose() {
      this.$refs[this.actFormName].resetFields()
      this[this.actFormName].pic = ''
      if (this.actFormName === 'addForm') {
        this.addForm.pid = []
      }
      this.editPic = []
      if (this.$refs[this.actUploadName]) this.$refs[this.actUploadName].clearFiles() // 删除预览
      this.actFormName = ''
      this.actUploadName = ''
    },

    // 关闭弹出前操作(不包括取消按钮)
    handleClose() {
      return done => {
        this.myClose()
        done()
      }
    },
    // 取消按钮
    close() {
      this.myClose()
      this[this.actvisibleName] = false
    },
    send() {
      this.$refs[this.actFormName].validate(async valid => {
        if (valid) {
          switch (this.actFormName) {
            case 'editForm': // 编辑司机
              try {
                await editCate(this.editForm)
                this.close()
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加模板
              try {
                await addCate(this.addForm)
                this.close()
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
.input-with-select {
  width: 110px;
}
.middle {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f2f2f2;
}
.middle:last-child {
  padding: 0;
  border: 0;
  padding-top: 20px;
}
.class-name {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}
.tag-right {
  margin: 2px;
  // padding: 5px;
}
</style>
